/*================================================================*
        Copyright (C) 2021 All rights reserved, www.hsby.link.
      	�ļ����ƣ�test_socket_stream.cc
      	�� �� �ߣ���ɭ����
      	�������ڣ�2021/12/30
 *================================================================*/

#include "socket_stream.h"
#include "iomanager.h"
#include "http/http.h"

void test_socket_stream() {
    auto addr = std::dynamic_pointer_cast<hsby::Ipv4Address>(hsby::BaseAddress::LookUpAny("www.baidu.com", AF_INET, SOCK_STREAM));
    if (!addr) {
        //HSBY_LOG_SYSTEM_DEBUG << "Lookup error";
    }
    addr->SetPort(80);
    //HSBY_LOG_SYSTEM_DEBUG << *addr;
    auto sock = hsby::Socket::CreateTCP(addr);
    if (!sock->Connect(addr)) {
        //HSBY_LOG_SYSTEM_DEBUG << "Connect fail, " << HSBY_VARS_EXP(sock->ToString());
    }
    //HSBY_LOG_SYSTEM_DEBUG << "Connect success!";
    auto ba = hsby::ByteArray::Create();
    hsby::http::HttpRequest request;
    request.SetMethod(hsby::http::HttpMethod::GET);
    request.SetPath("/");
    auto request_str = request.ToString();
    ba->Write(request_str.c_str(), request_str.size());
    //HSBY_LOG_SYSTEM_DEBUG << "\n" << ba->DataToTextString();
    hsby::SocketStream ss(sock);
    int ret = ss.Write(ba, ba->GetWritePos());
    HSBY_LOG_SYSTEM_DEBUG << HSBY_VARS_EXP(ret, ba->GetReadPos());
    ba->Clear();
    ret = ss.Read(ba, 40960);
    //HSBY_LOG_SYSTEM_DEBUG << HSBY_VARS_EXP(ret);
    //HSBY_LOG_SYSTEM_DEBUG << "\n" << ba->DataToTextString();
}

int main() {
    hsby::IoManager iom(1, "TestSocketStream");
    iom.AddTask(test_socket_stream);
    return 0;
}